package com.jingge.autojob.skeleton.cluster.api;

import com.jingge.autojob.skeleton.annotation.AutoJobRPCService;
import com.jingge.autojob.skeleton.framework.boot.AutoJobApplication;
import com.jingge.autojob.skeleton.framework.config.AutoJobConstant;
import com.jingge.autojob.skeleton.framework.task.AutoJobTask;
import com.jingge.autojob.skeleton.lifecycle.TaskEventFactory;
import com.jingge.autojob.skeleton.lifecycle.event.imp.TaskMissFireEvent;
import com.jingge.autojob.skeleton.lifecycle.manager.TaskEventManager;
import com.jingge.autojob.util.convert.DateUtils;
import lombok.extern.slf4j.Slf4j;

/**
 * @author JingGe(* ^ ▽ ^ *)
 * @date 2023-09-22 10:14
 * @email 1158055613@qq.com
 */
@AutoJobRPCService("defaultCallbackAPI")
@Slf4j
public class DefaultCallbackAPI implements CallbackAPI {
    @Override
    public Boolean refreshed(AutoJobTask refreshedTask) {
        if (refreshedTask != null && refreshedTask.getTrigger() != null) {
            if (refreshedTask
                    .getTrigger()
                    .isNearTriggeringTime(AutoJobConstant.dbSchedulerRate * 2)) {
                AutoJobApplication
                        .getInstance()
                        .getRegister()
                        .registerTask(refreshedTask);
            } else if (refreshedTask
                    .getTrigger()
                    .getTriggeringTime() > System.currentTimeMillis() || System.currentTimeMillis() - refreshedTask
                    .getTrigger()
                    .getTriggeringTime() < 1000) {
                log.warn("任务：{}-{}missFire",refreshedTask.getId(),
                        DateUtils.formatDate(refreshedTask.getTrigger().getTriggeringTime(),"yyyy-MM-dd HH:mm:ss"));
                TaskEventManager
                        .getInstance()
                        .publishTaskEvent(TaskEventFactory.newTaskMissFireEvent(refreshedTask), TaskMissFireEvent.class, true);
            }
            return true;
        }
        return false;
    }
}
